package com.xiaoding.serialhelper;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaoding.tcp.*;


import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;


/**
 * Created by Administrator on 2017/5/20 0020.
 */

public class CommSettingActivity  extends AppCompatActivity  {
    private static final String TAG = "CommSettingActivity";

    //按钮控件
    private Button btu_confirm;
    private  Button btn_cancle;

    //复选按钮控件
    private CheckBox  hex_show;
    private  CheckBox auto_huang;
    private  CheckBox hex_send;
    private  CheckBox auto_send;
    //文本显示控件
    private TextView ip_mode;
    private TextView port_mode;

    //编辑框控件
    private EditText edit_ip;
    private EditText edit_port;
    private EditText edit_time;

    //下拉控件
    private Spinner link_mode;                       //连接模式

    //网络连接模式选择
    private int ch_mode=0;
    //TCP服务器通信模式下
    private TCP_service tcp_service =null;
    private int ser_port;
    private boolean ser_islink=false;
    private boolean client_islink =false;

    //复选状态信息
    private boolean  Hex_show =false;
    private boolean  Auto_huang =false;
    private boolean  Hex_send =false;
    private boolean  Auto_send =false;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
   //     requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.comm_type);
        init(savedInstanceState);

        link_mode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ch_mode = position;
                if (ch_mode == MainActivity.MODE_TCP_SERVER) {
                    ip_mode.setText("本地 I P");
                    edit_ip.setEnabled(false);
                    port_mode.setText("本地端口");
                    btu_confirm.setText("启动");
                    edit_ip.setText(getLocalIpAddress());   //获取本地IP地址显示

                }
                if (ch_mode == MainActivity.MODE_TCP_CLIENT) {
                    edit_ip.setEnabled(true);
                    ip_mode.setText("目的 I P");
                    port_mode.setText("目的端口");
                }
                if(ch_mode ==MainActivity.MODE_UDP_Server )
                {
                    ip_mode.setText("本地 I P");
                    edit_ip.setEnabled(false);
                    port_mode.setText("本地端口");
                    btu_confirm.setText("启动");
                    edit_ip.setText(getLocalIpAddress());   //获取本地IP地址显示
                }
                if(ch_mode == MainActivity.MODE_UDP_Cleint)
                {
                    edit_ip.setEnabled(true);
                    ip_mode.setText("目的 I P");
                    port_mode.setText("目的端口");
                }

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        edit_ip.setText(getLocalIpAddress());   //获取本地IP地址显示
        edit_port.setText(8080+"");             //设置默认端口号
        btu_confirm.setOnClickListener(confirmListener);
        btn_cancle.setOnClickListener(cancleListener);


        hex_send.setOnCheckedChangeListener(listener);
        hex_show.setOnCheckedChangeListener(listener);
        auto_huang.setOnCheckedChangeListener(listener);
        auto_send.setOnCheckedChangeListener(listener);
    }

    //初始化控件函数
    private void init(Bundle savedInstanceState) {
        link_mode= (Spinner) findViewById(R.id.ch_mode);
        ip_mode= (TextView) findViewById(R.id. ip_mode);
        port_mode= (TextView) findViewById(R.id.port_mode);

        edit_ip= (EditText) findViewById(R.id.ip_edit);
        edit_port= (EditText) findViewById(R.id.port_edit);
        edit_time= (EditText) findViewById(R.id.edi_auto);

        hex_show= (CheckBox) findViewById(R.id.hex_show);
        auto_huang= (CheckBox) findViewById(R.id.autohuang);
        hex_send= (CheckBox) findViewById(R.id.hex_send);
        auto_send= (CheckBox) findViewById(R.id.auto_send);

        btu_confirm = (Button) findViewById(R.id.confirm_button);
        btn_cancle =(Button) findViewById(R.id.cancle_button);

      //  edit_ip.setText(getLocalIpAddress());

        Bundle bundle = this.getIntent().getExtras();
        String ip = bundle.getString("ip").replaceAll("\\s*", "");
        if(ip == "0.0.0.0") {
            edit_ip.setText(getLocalIpAddress());
        }else
        {
            edit_ip.setText(ip);
        }
        Integer port = bundle.getInt("port",0);
        if((port != 0) || (port !=8080)) {
            edit_port.setText(String.valueOf(port));
        }

    }

    private OnCheckedChangeListener listener =new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()){
                case R.id.hex_show:
                    if (isChecked) {
                        Toast.makeText(CommSettingActivity.this, "16进制显示",
                                Toast.LENGTH_SHORT).show();
                        Hex_show = true;
                       // Log.i(TAG, "onCheckedChanged:  Hex_show status is:" + MainActivity.Hex_show);
                    } else
                        Hex_show = false;

                    break;
                case R.id.autohuang:
                    if (isChecked) {
                        Toast.makeText(CommSettingActivity.this, "自动换行",
                                Toast.LENGTH_SHORT).show();
                        Auto_huang = true;
                    } else
                        Auto_huang = false;
                    break;
                case R.id.hex_send:
                    if (isChecked) {
                        Toast.makeText(CommSettingActivity.this, "16进制发送",
                                Toast.LENGTH_SHORT).show();
                        Hex_send = true;
                    } else
                        Hex_send = false;

                    break;
                case R.id.auto_send:
                    if (isChecked) {
                        Toast.makeText(CommSettingActivity.this, "16进制发送",
                                Toast.LENGTH_SHORT).show();
                        Auto_send = true;
                    } else
                        Auto_send = false;

                    break;
            }
        }
    };

    private View.OnClickListener confirmListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent =new Intent();

            intent.putExtra("Hex_show",Hex_show);
            intent.putExtra("Hex_send",Hex_send);
            intent.putExtra("Auto_send",Auto_send);
            intent.putExtra("Auto_huang",Auto_huang);

            if (ch_mode==MainActivity.MODE_TCP_SERVER){
                intent.putExtra("comm_mode",ch_mode);
                intent.putExtra("ip",edit_ip.getText().toString());
                intent.putExtra("port",edit_port.getText().toString());
            }
            if(ch_mode==MainActivity.MODE_TCP_CLIENT){
                intent.putExtra("comm_mode",ch_mode);
                intent.putExtra("ip",edit_ip.getText().toString());
                intent.putExtra("port",edit_port.getText().toString());
            }
            if(ch_mode == MainActivity.MODE_UDP_Server)
            {
                intent.putExtra("comm_mode",ch_mode);
                intent.putExtra("ip",edit_ip.getText().toString());
                intent.putExtra("port",edit_port.getText().toString());
            }
            if(ch_mode == MainActivity.MODE_UDP_Cleint)
            {
                intent.putExtra("comm_mode",ch_mode);
                intent.putExtra("ip",edit_ip.getText().toString());
                intent.putExtra("port",edit_port.getText().toString());
            }
            if(ch_mode == MainActivity.MODE_Bluetooth)
            {
                intent.putExtra("comm_mode",ch_mode);
            }

            setResult(RESULT_OK,intent);
            finish();
        }
    };

    private View.OnClickListener cancleListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent =new Intent();
            if (ch_mode==MainActivity.MODE_TCP_SERVER){
                intent.putExtra("comm_mode",ch_mode);
                intent.putExtra("port",edit_port.getText().toString());
            }
            if(ch_mode ==MainActivity. MODE_TCP_CLIENT){
                intent.putExtra("comm_mode",ch_mode);
                intent.putExtra("ip",edit_ip.getText().toString());
                intent.putExtra("port",edit_port.getText().toString());
            }
            setResult(RESULT_CANCELED,intent);
            finish();

        }

    };

    //获取wifi本地IP和主机名
    private String getLocalIpAddress() {
        String ip=null;
        try {
            ConnectivityManager conMann = (ConnectivityManager)
                    this.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netkInfo = conMann.getActiveNetworkInfo();

            if (netkInfo != null) {
                if (netkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    ip = getMobleIpAddress();
                    System.out.println("本地ip-----" + ip);
                } else if (netkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    ip = getWifiIpAddress();
                }
            } else {
                ip = "0.0.0.0";
            }
        }catch (Exception  ex)
        {
            Log.e("getLocalIpAddress", ex.toString());
        }
        if(ip == null)
        {
            ip="0.0.0.0";
        }
        return  ip;
    }

    //获取wifi本地IP和主机名
    private String getWifiIpAddress() {
        String ip="";
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        // 获取32位整型IP地址
        int ipAddress = wifiInfo.getIpAddress();

        //返回整型地址转换成“*.*.*.*”地址
        ip= String.format("%d.%d.%d.%d",
                (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
        return ip;
    }


    public String getMobleIpAddress() {
        String ip=null;
        try {
            for (final Enumeration<NetworkInterface> enumerationNetworkInterface = NetworkInterface.getNetworkInterfaces(); enumerationNetworkInterface.hasMoreElements();) {
                final NetworkInterface networkInterface = enumerationNetworkInterface.nextElement();
                for (Enumeration<InetAddress> enumerationInetAddress = networkInterface.getInetAddresses(); enumerationInetAddress.hasMoreElements();) {
                    final InetAddress inetAddress = enumerationInetAddress.nextElement();
                    final String ipAddress = inetAddress.getHostAddress();
                    if ( (!inetAddress.isLoopbackAddress()) && (inetAddress instanceof  Inet4Address)  ) {
                        ip = ipAddress;
                    }
                }
            }
        }
        catch (final Exception e) {
            //  LogHelper.wtf(null, e);
            // return null;
            Log.e("getMobleIpAddress",e.toString());
        }
        if(null == ip)
        {
            ip="0.0.0.0";
        }
        return ip;
    }


}
